package org.example.eatback.controller;



import org.example.eatback.service.DiaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/api/diary")
@CrossOrigin(origins = "http://localhost:5173")
@Slf4j
public class DiaryController {

    @Autowired
    private DiaryService diaryService;



    @PostMapping("/{username}/meal/{mealType}")
    public ResponseEntity<?> updateMeal(
            @PathVariable String username,
            @PathVariable String mealType,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @RequestBody HashMap<String, Object> mealData) {
        try {
            diaryService.updateMeal(
                    username,
                    date,
                    mealType,
                    (String) mealData.get("foods"),
                    (Integer) mealData.get("calories"),
                    (String) mealData.get("notes")
            );
            return ResponseEntity.ok(new HashMap<String, String>() {{
                put("message", "保存成功");
            }});
        } catch (Exception e) {
            log.error("保存餐饮记录失败", e);
            return ResponseEntity.status(500).body(new HashMap<String, String>() {{
                put("message", "保存数据失败");
            }});
        }
    }

    @DeleteMapping("/{username}/meal/{mealType}")
    public ResponseEntity<?> deleteMeal(
            @PathVariable String username,
            @PathVariable String mealType,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        try {
            diaryService.deleteMeal(username, date, mealType);
            return ResponseEntity.ok(new HashMap<String, String>() {{
                put("message", "删除成功");
            }});
        } catch (Exception e) {
            log.error("删除餐食记录失败", e);
            return ResponseEntity.status(500).body(new HashMap<String, String>() {{
                put("message", "删除失败");
            }});
        }
    }
}
